import { Button, Menu } from "@arco-design/web-react"
import { IconBook, IconDashboard, IconFolder, IconHome, IconImage, IconMenuFold, IconNav, IconUser, IconUserGroup } from '@arco-design/web-react/icon';
import { useEffect, useRef, useState } from "react";
import useRoute, { IRoute } from "../router";
import './style/Sider.less'
import { useLocation } from "react-router-dom";
import qs from 'query-string'
// import NProgress from 'nprogress'
import { useNavigate } from "react-router-dom";

const MenuItem = Menu.Item;
const SubMenu = Menu.SubMenu;

export default function Siderbar(props: any) {
    const navigate = useNavigate()
    const locale = {
        'menu.home':'Home',
        'menu.home.list': 'List',
        'menu.advertising': '广告管理',
        'menu.advertising.advertisers': '广告主',
        'menu.advertising.plan': '广告计划',
        'menu.advertising.plan.form': '广告计划表单',
        'menu.advertising.data-report': '数据报表',
        'menu.advertising.campaign': '广告活动',
        'menu.advertising.campaign.form': '广告活动表单',
        'menu.advertising.agentChannel': '代理渠道',
        'menu.attribution': '归因事件管理',
        'menu.attribution.manage': '广告归因事件管理',
        'menu.report': '数据报表',
        'menu.report.totalIncome': '广告整体收入报表',
        'menu.crowd': '人群管理',
        'menu.crowd.manage': '人群包管理',
        'menu.crowd.manage.create': '创建',
        'menu.crowd.manage.edit': '编辑',
        'menu.resource': '资源位管理',
        'menu.resource.position': '版位管理',
        'menu.resource.resource-place': '广告位管理',
        'menu.resource.template-ins': '规格管理',
    }
    const routeMap = useRef<Map<string, React.ReactNode[]>>(new Map());
    const menuMap = useRef<
        Map<string, { menuItem?: boolean; subMenu?: boolean }>
    >(new Map());
    const { pathname } = useLocation();
    const currentComponent = qs.parseUrl(pathname).url.slice(1);
    const [route, defaultRoute] = useRoute();
    const defaultSelectedKeys = [currentComponent || defaultRoute];
    const paths = (currentComponent || defaultRoute).split('/');
    const [openKeys, setOpenKeys] = useState<string[]>(defaultSelectedKeys)
    const [selectedKeys, setSelectedKeys] =
        useState<string[]>(defaultSelectedKeys);
    const { permissionRoute, routes } = props
    const { menuChange } = props;
    const [collapsed, setCollapsed] = useState(false)
    const handleOnCollapseChange = () => {
        menuChange()
    }
    function getIconFromKey(key: any) {
        switch (key) {
            case 'dashboard':
                return <IconDashboard className="icon" />;
            case 'advertising':
                return <IconUser className="icon" />;
            case 'attribution':
                return <IconBook className="icon" />;
            case 'report':
                return <IconImage className="icon" />;
            case 'programmatic':
                return <IconFolder className="icon" />;
            case 'resource':
                return <IconNav className="icon" />;
            case 'crowd':
                return <IconUserGroup className="icon" />;
            case 'home':
                return <IconHome className="icon"/>
            default:
                return <div className='icon-empty' />;
        }
    }
    function renderRoutes() {
        routeMap.current.clear();
        return function travel(_routes: IRoute[], level: any, parentNode = []) {
            return _routes?.map((route) => {
                const { breadcrumb = true, ignore } = route;
                const iconDom = getIconFromKey(route.key);
                const titleDom = (
                    <>
                        {iconDom} {locale[route.name as keyof typeof locale]}
                    </>
                );
                routeMap.current.set(
                    `/${route.key}`,
                    breadcrumb ? [...parentNode, route.name] : [],
                );
                const visibleChildren = (route.children || []).filter((child) => {
                    const { ignore, breadcrumb = true } = child;
                    if (ignore || route.ignore) {
                        routeMap.current.set(
                            `/${child.key}`,
                            breadcrumb ? [...parentNode, route.name, child.name] : [],
                        );
                    }
                    return !ignore;
                });
                if (ignore) {
                    return '';
                }
                if (visibleChildren.length) {
                    menuMap.current.set(route.key, { subMenu: true });
                    return (
                        <SubMenu key={route.key} title={titleDom}>
                            {travel(visibleChildren, level + 1, [...parentNode, route.name])}
                        </SubMenu>
                    );
                }
                menuMap.current.set(route.key, { menuItem: true });
                return <MenuItem key={route.key}>{titleDom}</MenuItem>;
            });
        };
    }
    function handleMenu(key:any) {
        
        const { routes } = props;
        const route = routes.find((r: {key: string}) => r.key === key);
        console.log(key, route)
        // const currentRoute = routes.find((r) => r.key === key);
        // NProgress.start();
        navigate(route.path ? route.path : `/${key}`);
        // setSelectedKeys([key]);
        // NProgress.done();
    }
    function updateMenuStatus() {
        const pathKeys = pathname.split('/');
        const newSelectedKeys: string[] = [];
        const newOpenKeys: string[] = [...openKeys];
        while (pathKeys.length > 0) {
            const currentRouteKey = pathKeys.join('/');
            const menuKey = currentRouteKey.replace(/^\//, '');
            const menuType = menuMap.current.get(menuKey);
            if (menuType && menuType.menuItem) {
                newSelectedKeys.push(menuKey);
            }
            if (menuType && menuType.subMenu && !openKeys.includes(menuKey)) {
                newOpenKeys.push(menuKey);
            }
            pathKeys.pop();
        }
        setSelectedKeys(newSelectedKeys);
        setOpenKeys(newOpenKeys);
    }

    // 根据路由选中菜单
    const setDefaultMenuSelect = (name: string) => {
        const menuKey = name.split('.');
        menuKey.shift();
        // 判断路由层级多于三级才去除最后一级
        if (menuKey.length > 2) {
            menuKey.pop();
        }
        const menuKeyStr = menuKey.join('/');
        setSelectedKeys([menuKeyStr]);
    };
    useEffect(() => {
        
        updateMenuStatus();
        if (routeMap.current.size > 0) {
            const routeConfig = routeMap.current.get(pathname);
            if (routeConfig) {
                // setBreadCrumb(routeConfig || []);
            } else {
                // setDefaultBreadCrumb();
            }
        } else {
            // setDefaultBreadCrumb();
        }
    }, [pathname]);
    // console.log(permissionRoute)
    return (
        <>
            <div className='menu-demo'>
                <Menu
                    onClickMenuItem={handleMenu}
                    accordion
                    collapse={collapsed}
                    openKeys={openKeys}
                    selectedKeys={selectedKeys}
                    onClickSubMenu={(_, openKeys) => setOpenKeys(openKeys)}
                >
                    {renderRoutes()(permissionRoute, 1)}
                </Menu>
                <Button
                    icon={<IconMenuFold />}
                    onClick={() => { setCollapsed(!collapsed); handleOnCollapseChange() }}
                    className="sidebar-toggle-button"></Button>
            </div>
        </>
    )
}